﻿using System;
using System.Collections.Generic;
using Grundy.Administration.Web.Services;
using Grundy.Entity;
using Grundy.Common;
using System.Linq;
using Grundy.Message;

namespace Grundy.Administration.Web.Models
{
    public class LicenseViewModel
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public string ClientTypes { get; set; }
        public long Limit { get; set; }
        public string Feature { get; set; }

        public Tuple<bool, string, License> ToLicense(FeatureService featureService)
        {
            var feature = featureService.GetFeature(Feature);
            if(feature == null)
                return Tuple.Create(false, "Cannot find feature with name '{0}'".FormatWith(Feature), (License)null);
            switch ((Type??  string.Empty).ToUpperInvariant())
            {
                case "NODELOCKEDLICENSE":
                    var nodeLockedLicense = new NodeLockedLicense {Name = Name, Feature = featureService.GetFeature(Feature.Trim())};
                    return Tuple.Create(true, string.Empty, (License)nodeLockedLicense);
                case "UNCOUNTEDFLOATINGLICENSE":
                    var uncountedFloatingLicense = new UncountedFloatingLicense {Name = Name, Feature = featureService.GetFeature(Feature.Trim()), Client = GetLicenseClientType(ClientTypes)};
                    return Tuple.Create(true, string.Empty, (License)uncountedFloatingLicense);
                case "CONCURRENTCOUNTEDFLOATINGLICENSE":
                    var concurrentCountedFloatingLicense = new CountedFloatingLicense { Name = Name, Feature = featureService.GetFeature(Feature.Trim()), Client = GetLicenseClientType(ClientTypes), Limit = Limit, LimitType = FloatingLicenseLimitType.Concurrency };
                    return Tuple.Create(true, string.Empty, (License)concurrentCountedFloatingLicense);
                case "EXECUTIONSCOUNTEDFLOATINGLICENSE":
                    var executionCountedFloatingLicense = new CountedFloatingLicense { Name = Name, Feature = featureService.GetFeature(Feature.Trim()), Client = GetLicenseClientType(ClientTypes), Limit = Limit, LimitType = FloatingLicenseLimitType.Execution };
                    return Tuple.Create(true, string.Empty, (License)executionCountedFloatingLicense);
                default:
                    return Tuple.Create(false, "Cannot find license type '{0}'".FormatWith(Type), (License)null);
            }
        }

        private LicenseClientType GetLicenseClientType(string s)
        {
            var licenseClientType = new[] {LicenseClientType.Checkout, LicenseClientType.Machine, LicenseClientType.Process, LicenseClientType.TerminalServicesSession, LicenseClientType.User}.Where(i => i.Name.EqualsIgnoreCase(s)).Single();
            return licenseClientType;
        }
    }
}